﻿// -----------------------------------------------------------------------
// <copyright file="CacheItem.cs" company="EPAM Systems">
////Copyright (c) EPAM Systems. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

namespace Epam.PhotoGallery.Bussines.CacheManager
{
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using System.Web.Caching;
	using Epam.PhotoGallery.Bussines.Configuration;



	public class CacheItem
	{
		/// <summary>
		/// Cache item times list.
		/// </summary>
		private IList<DateTime> queue;
		public DateTime TimeLast { get; set; }

		public CacheItem(DateTime time)
		{
			this.queue = new List<DateTime>();
			this.queue.Add(time);
			this.TimeLast = time;
		}

		public bool IsNeedToAddCache(CacheItemPrioritySection configuration)
		{
			var result = false;
			
			if (this.queue.Count >=  configuration.MinCounter)
			{
				var requestsPeriod = this.queue.First().Ticks - this.queue.Last().Ticks;
				var maxOptionPeriod = TimeSpan.FromSeconds(configuration.Low).Ticks;
				
				result = requestsPeriod <= maxOptionPeriod;
			}
			
			this.queue.Add(DateTime.Now);
			
			return result;
		}

		public CacheItemPriority GetCurrentCachePriority(CacheItemPrioritySection configuration)
		{
			var requestsPeriod = this.queue.First().Ticks - this.queue.Last().Ticks;
			CacheItemPriority result = CacheItemPriority.Default;
			
			this.queue.RemoveAt(0);
			
			if (requestsPeriod <= TimeSpan.FromSeconds(configuration.Low).Ticks)
			{
				result = CacheItemPriority.Low;
				if (requestsPeriod <= TimeSpan.FromSeconds(configuration.Normal).Ticks)
				{
					result = CacheItemPriority.Normal;
					if (requestsPeriod <= TimeSpan.FromSeconds(configuration.High).Ticks)
					{
						result = CacheItemPriority.High;
					}
				}
			}
			
			return result;
		}

		public void Clear()
		{
			this.queue.Clear();
		}
	}
}
